package filescript;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import exceptions.BadOrderException;
import exceptions.CmdFileNotFoundException;
import exceptions.SrcDirNotFoundException;
import exceptions.UsageException;
import exceptions.WrongArgsOrderException;


public class MyFileScript {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//CHECK VALIDITY OF ARGS - file and source dir
		
		ArrayList<File> importedFiles = new ArrayList<File>();
		ArrayList<Section> secs = new ArrayList<Section>();
		FileAnalyzer analyzer = null;
		File cmdFile = null;
		SectionManager theManager = null;
		
		//tester
		try {
			cmdFile = checkArgs(args);
			importFiles(importedFiles,args[0]);
			analyzer = new FileAnalyzer(args[0], cmdFile);
			secs = analyzer.analyze();
			for (Section sec : secs){
				theManager = new SectionManager(importedFiles);
				theManager.runSection(sec, importedFiles);
			}				
			//processCmdFile;
		}
		//ADD MORE EXCEPTIONS CATCH - HANDLE ACTIONS!!!
		catch (exceptions.FileScriptException e){
			System.err.println("Error");
			System.exit(-1);
		}
		catch (IOException e){
			System.err.println("Error");
			System.exit(-1);
		}
		
		

	}
	
	
	
	public static File checkArgs(String[] args) throws UsageException {
		if ((args == null) || (args.length != 2))
			throw new UsageException();
		
		File path = new File(args[0]);
		File cmdFile = new File(args[1]);
		
		if (!path.exists())
			throw new SrcDirNotFoundException();
		
		if (!cmdFile.exists())
			throw new CmdFileNotFoundException();
		
		if(!path.isDirectory() || !cmdFile.isFile())
			throw new WrongArgsOrderException();
		
		return cmdFile;
			
	}
	
	public static void importFiles(ArrayList<File> importInto, String path)
									throws IOException{
		File header = new File(path);
		addFiles(header.listFiles(), importInto);
		
	}
	
	private static void addFiles(File[] filesToAdd, ArrayList<File> importInto)
						throws IOException {
		for (int i = 0; i < filesToAdd.length; i++) {
			String filePath = filesToAdd[i].getCanonicalPath();
			if (new File(filePath).isFile())
				importInto.add(new File(filePath));
			else
				addFiles(new File(filePath).listFiles(), importInto);
		}

		
	}
	

}
